package xmlMapping;

import xmlMapping.lts.CurrencyRate;
import xmlMapping.model.Computer;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.text.SimpleDateFormat;
import java.util.List;

public class SaveOrUpdate {
    private static SessionFactory factory;

    public static void main(String[] args) {
        ApplicationContext context = new FileSystemXmlApplicationContext("conf/beans.xml");
        factory = context.getBean(SessionFactory.class);

        selectById(1);
    }

    public static Computer selectById(int id) {
        Session session = factory.openSession();
        Query query = session.createQuery("from Computer where id = :id");
        query.setParameter("id", 1);
        return (Computer) query.getSingleResult();
    }

    public static void saveOrUpdate() {
        Session session = factory.openSession();
        try {
            Transaction tx = session.beginTransaction();

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            CurrencyRate r1 = new CurrencyRate();
            r1.setSymbol("CNHHKD");
            r1.setPrice(1.236645);
            r1.setTradeDate(format.parse("2018-03-03"));

            CurrencyRate r2 = new CurrencyRate();
            r2.setSymbol("CNHHKD");
            r2.setPrice(1.236640);
            r2.setTradeDate(format.parse("2018-03-03"));

            Session finalSession = session;

            finalSession.saveOrUpdate(r1);
            finalSession.saveOrUpdate(r2);
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
    }

}
